package com.ruitaowang.wap;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.security.PermitAll;

import com.alibaba.fastjson.JSON;
import com.ruitaowang.account.service.WalletService;
import com.ruitaowang.core.domain.*;
import com.ruitaowang.core.utils.Md5TokenGenerator;
import com.ruitaowang.goods.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.ruitaowang.account.security.LYSecurityUtil;
import com.ruitaowang.account.service.RoleService;
import com.ruitaowang.account.service.SysUserService;
import com.ruitaowang.core.properties.ConfigProperties;
import com.ruitaowang.core.utils.LYBeanUtils;
import com.ruitaowang.core.utils.RandomUtils;
import com.ruitaowang.core.web.BaseController;
import com.ruitaowang.core.web.MsgOut;

import wx.wechat.common.Configure;
import wx.wechat.service.mp.MPService;

/**
 * Created by neal on 12/17/16.
 */
@Slf4j
@RestController
public class WapController extends BaseController {
	
	@Autowired
	WxClientCredentialService wxClientCredentialService;
	@Autowired
	private WXUserinfoService wxUserinfoService;
	@Autowired
	private SysUserService userService;
	@Autowired
	ConfigProperties configProperties;
    @Autowired
	private WalletService walletService;
	@Value("${host.api}")
	private String host;

	/**
	 * 登录
	 *
	 * @param code
	 * @return
	 */
	@RequestMapping("/wx/login")
	public String createUserWrapper(String code) throws InvocationTargetException, IllegalAccessException {
		if (StringUtils.hasLength(code)) {
				LOGGER.error("token {}", code);
			MPService mpService = new MPService();
			//设置缓存 code: map
			Map<String, String> token = null;
			try {
				token = mpService.fetchAccessTokenByCode4Authorization(code);
				log.info(JSON.toJSONString(token));
				LOGGER.error("token {}", token);
			SNSWXUserinfo snswxUserinfo = wxUserinfoService.selectByOpenId(token.get("openid"));
				// check bind mobile
			SysUserVO sysUserVO = new SysUserVO();
			if (ObjectUtils.isEmpty(snswxUserinfo)) {
						snswxUserinfo = new SNSWXUserinfo();
						LYBeanUtils.copyPropertiesFromMapToBean(token, snswxUserinfo);
						snswxUserinfo.setAccessToken(token.get("access_token"));
						snswxUserinfo.setExpiresIn(Integer.valueOf(token.get("expires_in")));
						Map<String, String> wxUser = mpService.fetchUserinfoByAccessToken(
								snswxUserinfo.getAccessToken(), snswxUserinfo.getOpenid());
						if (StringUtils.isEmpty(wxUser.get("errcode"))) {
							LYBeanUtils.copyPropertiesFromMapToBean(wxUser, snswxUserinfo);
							// 第一次登陆
							SysUser user = new SysUser();
							user.setUsername(RandomUtils.randomString(8));
							user.setPassword(RandomUtils.randomString(8));
							user.setNickname(snswxUserinfo.getNickname());
							user.setHeadimgurl(snswxUserinfo.getHeadimgurl());
							user.setLastTime(System.currentTimeMillis());
							userService.insert(user);
							Wallet wallet = new Wallet();
							wallet.setUserId(user.getId());
							wallet.setUserName(user.getNickname());
							walletService.insert(wallet);
							BeanUtils.copyProperties(user,sysUserVO);
							sysUserVO.setUserInfoType((byte)1);
							snswxUserinfo.setUserId(user.getId());
							wxUserinfoService.insert(snswxUserinfo);
							LOGGER.error("user {}", user);
						}
				}else {
				SysUser sysUser=userService.selectByPK(snswxUserinfo.getUserId());

				//更新用户数据
					if (ObjectUtils.isEmpty(snswxUserinfo.getUnionid())) {
						snswxUserinfo.setAccessToken(token.get("access_token"));
						Map<String, String> updateUnionidMap = mpService.fetchUserinfoByAccessToken(
								snswxUserinfo.getAccessToken(), snswxUserinfo.getOpenid());
						snswxUserinfo.setUnionid(updateUnionidMap.get("unionid"));
						wxUserinfoService.update(snswxUserinfo);
						LYBeanUtils.copyPropertiesFromMapToBean(updateUnionidMap, snswxUserinfo);
						sysUser.setNickname(snswxUserinfo.getNickname());
						sysUser.setHeadimgurl(snswxUserinfo.getHeadimgurl());
						sysUser.setLastTime(System.currentTimeMillis());
						userService.update(sysUser);
						Wallet wallet = new Wallet();
						wallet.setUserId(sysUser.getId());
						wallet.setUserName(sysUser.getNickname());
						walletService.update(wallet);
					}
					//返回是否有完善信息
					LOGGER.error("user {}", sysUser);
					BeanUtils.copyProperties(sysUser,sysUserVO);
					if (!ObjectUtils.isEmpty(sysUser.getPhone())){
						sysUserVO.setUserInfoType((byte)1);
					}
				}
			sysUserVO.setToken(Md5TokenGenerator.generate(sysUserVO.getUsername(),sysUserVO.getPassword()));
			return JSON.toJSONString(MsgOut.success(sysUserVO));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return "";
	}

	@RequestMapping(value = { "/test/wap/enroll/{fk}" })
	public ModelAndView test(@RequestParam String code, @PathVariable String fk) {
		return new ModelAndView("redirect:/wap/enroll/" + fk + "?code=" + code);
	}

	@RequestMapping(value = { "/wap/configure" })
	public String configure() {
		return this.renderJson(MsgOut.success(Configure.hostWap));
	}

	@RequestMapping(value = { "/wap/properties" })
	@PermitAll
	public String configProperties() {
		return this.renderJson(MsgOut.success(configProperties));
	}
}
